﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Talentnet.Core.Web;
using Talentnet.Core.Utilities.Cryptophy;

[PageTextResource("Login")]
public partial class global_login : NormalPage
{
    const string LOGIN_FAILED_COOKIE = "failed";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            EvalutateForgotPwd();
        }
        ctrlMsg.Text = "";
        ctrlCaptcha.Visible = false;
        if (Request.Cookies[LOGIN_FAILED_COOKIE] != null)
        {
            if (int.Parse(Request.Cookies[LOGIN_FAILED_COOKIE].Value) >= 2)
            {
                ctrlCaptcha.Visible = true;
                
                ctrlCaptcha.CaptchaLinkButtonText = LoadText("Login", "ctrlCaptcha");
                ctrlCaptcha.ErrorMessage = LoadText("Login", "CaptchaErrorMessage");
            }
        }
        ctrlCaptchaCodeBlock.Visible = ctrlCaptcha.Visible;
        

    }


    void DoInvalidLogin()
    {
        ctrlMsg.Text = LoadText("Login", "txtInvalidLogin");
        //Session.Clear();
        
        HttpCookie cookie = null;
        if (Request.Cookies[LOGIN_FAILED_COOKIE] != null)
        {
            cookie = new HttpCookie(LOGIN_FAILED_COOKIE, (int.Parse(Request.Cookies[LOGIN_FAILED_COOKIE].Value) + 1).ToString());
        }
        else
        {
            cookie = new HttpCookie(LOGIN_FAILED_COOKIE, "1");
        }
        cookie.HttpOnly = true;
        Response.Cookies.Add(cookie);
    }
    protected void ctrlOK_Click(object sender, EventArgs e)
    {
        if (ctrlCaptcha.Visible && !ctrlCaptcha.IsValid)
        {
            return;
        }
        if (string.IsNullOrEmpty(ctrlPassword.Text))
        {
            DoInvalidLogin();
            return;
        }
        int result = this.DBUser.Login(0, inLoginName.Text, CryptoAgent.Current.MD5(inPassword.Text), Request.UserHostAddress);
        
        switch (result)
        {
            case 1://login successfully
            case 2://nearly expired
            case 3://expired
            case 4://expired
            case 10://force reset password
                {
                    SessionManager.CurrentUser = this.DBUser.GetUserDetail(inLoginName.Text);
                    DataTable roles = this.DBUser.GetUserRoles(SessionManager.CurrentUser.RecId);
                    if (roles.Rows.Count <= 0)
                    {
                        DoInvalidLogin();
                        return;
                    }
                    switch (roles.Rows[0]["RoleCode"].ToString())
                    {
                        case SiteConstants.RoleCodes.ADMIN:
                            SessionManager.CurrentUserType = SiteEnums.UserType.Administrators;
                            break;
                        case SiteConstants.RoleCodes.CONSULTANT:
                            SessionManager.CurrentUserType = SiteEnums.UserType.Consultants;
                            break;
                        case SiteConstants.RoleCodes.MANAGER:
                            SessionManager.CurrentUserType = SiteEnums.UserType.Managers;
                            break;
                        case SiteConstants.RoleCodes.EMPLOYEE:
                            SessionManager.CurrentUserType = SiteEnums.UserType.Employees;
                            break;
                    }
                    DataTable pers = this.DBUser.GetUserPermissions(SessionManager.CurrentUser.RecId);
                    SessionManager.CurrentUserPermissions = new string[pers.Rows.Count];
                    for (int i = 0; i < pers.Rows.Count; i++)
                    {
                        SessionManager.CurrentUserPermissions[i] = pers.Rows[i]["PermissionCode"].ToString();
                    }
                    SessionManager.CurrentUserMenus = this.DBUser.GetUserMenus(SessionManager.CurrentUser.RecId);
                    SaveAutheticatedData(SessionManager.CurrentUser.RecId.ToString());
                    if (Request.Cookies[LOGIN_FAILED_COOKIE] != null)
                    {
                        Response.Cookies.Add(new HttpCookie(LOGIN_FAILED_COOKIE, "0"));
                    }
                    SessionManager.PwdNearlyExpired = result == 2;
                    SessionManager.PwdExpired = (result == 3 || result == 4 || result == 10);
                    if (SessionManager.PwdNearlyExpired || SessionManager.PwdExpired) Response.Redirect("resetPwd.aspx");
                    else Response.Redirect("default.aspx");
                }
                break;
            
            default:
                {
                    DoInvalidLogin();
                }
                return;
        }
        
    }
    void EvalutateForgotPwd()
    {
        if (IsStaticQueryString)
        {
            //if (DBUser.ValidateForgotPwdRequest(new Guid(SecureQueryString["uid"]), SecureQueryString["key"], Request.UserHostAddress) == 100)
            if(true)
            {
                SessionManager.CurrentUser = this.DBUser.GetUserDetail(new Guid(SecureQueryString["uid"]));
                DataTable roles = this.DBUser.GetUserRoles(SessionManager.CurrentUser.RecId);
                switch (roles.Rows[0]["RoleCode"].ToString())
                {
                    case SiteConstants.RoleCodes.ADMIN:
                        SessionManager.CurrentUserType = SiteEnums.UserType.Administrators;
                        break;
                    case SiteConstants.RoleCodes.CONSULTANT:
                        SessionManager.CurrentUserType = SiteEnums.UserType.Consultants;
                        break;
                    case SiteConstants.RoleCodes.MANAGER:
                        SessionManager.CurrentUserType = SiteEnums.UserType.Managers;
                        break;
                    case SiteConstants.RoleCodes.EMPLOYEE:
                        SessionManager.CurrentUserType = SiteEnums.UserType.Employees;
                        break;
                }
                DataTable pers = this.DBUser.GetUserPermissions(SessionManager.CurrentUser.RecId);
                SessionManager.CurrentUserPermissions = new string[pers.Rows.Count];
                for (int i = 0; i < pers.Rows.Count; i++)
                {
                    SessionManager.CurrentUserPermissions[i] = pers.Rows[i]["PermissionCode"].ToString();
                }
                SessionManager.CurrentUserMenus = this.DBUser.GetUserMenus(SessionManager.CurrentUser.RecId);
                SaveAutheticatedData(SessionManager.CurrentUser.RecId.ToString());
                SessionManager.PwdExpired = true;
                SessionManager.ResetPwd = true;
                Response.Redirect("resetPwd.aspx");
            }
        }
    }
    private void SaveAutheticatedData(string id)
    {
        FormsAuthenticationTicket ticket;
        ticket = new FormsAuthenticationTicket(1, id, DateTime.Now, DateTime.Now.AddMinutes(20), false, "");
        string hash = FormsAuthentication.Encrypt(ticket);
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
        cookie.Path = FormsAuthentication.FormsCookiePath;
        cookie.HttpOnly = true;
        cookie.Secure = FormsAuthentication.RequireSSL;
        Response.Cookies.Add(cookie);
    }
}
